import java.util.Random;

public class SaleThread implements Runnable {
    private final CDStore store;
    private final Logger logger;
    private final Thread restockThread;
    private final Random rand = new Random();

    public SaleThread(CDStore store, Logger logger, Thread restockThread) {
        this.store = store;
        this.logger = logger;
        this.restockThread = restockThread;
    }

    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                int cdType = rand.nextInt(10) + 1;
                int quantity = rand.nextInt(5) + 1;

                if (store.sell(cdType, quantity)) {
                    logger.log("Sold " + quantity + " of CD type " + cdType);
                    // 修改触发条件：当库存<=3时触发紧急补货
                    if (store.getStock(cdType) <= 3) {
                        store.setNeedsEmergencyRestock(true);
                    }
                } else {
                    if (rand.nextBoolean()) {
                        logger.log("Waiting for CD type " + cdType);
                        Thread.sleep(rand.nextInt(200));
                    } else {
                        logger.log("Abandoned sale of CD type " + cdType);
                    }
                }
                Thread.sleep(rand.nextInt(200));
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
